//
//  FPDFViewController.m
//  Foundation
//
//  Created by 吴新庭 on 2019/8/29.
//

#import "FPDFViewController.h"
#import "FPDFView.h"
#import <FImageEditViewController.h>

@interface FPDFViewController () <FPDFViewDelegate>

@property (nonatomic, strong) FPDFView *pdfView;

@end

@implementation FPDFViewController
@synthesize url = _url;

- (instancetype)initWithURL:(NSURL *)url {
    if (self = [super init]) {
        _url = url;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pdfView = [[FPDFView alloc] initWithFrame:CGRectZero pdf:self.url.path];
    self.pdfView.delegate = self;
    [self.view addSubview:self.pdfView];
    [self.pdfView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(0);
    }];
    self.pdfView.currentPage = self.currentPage;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.pdfView refresh];
    [UIView animateWithDuration:0.25 animations:^{
        self.pdfView.collectionView.contentOffset = _contentOffset;
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    if ([self.delegate respondsToSelector:@selector(pdfViewControllerDidDisappear:)]) {
        [self.delegate pdfViewControllerDidDisappear:self];
    }
}

- (void)setCurrentPage:(FPDFPage *)currentPage {
    _currentPage = currentPage;
    
    self.pdfView.currentPage = currentPage;
}

- (CGPoint)contentOffset {
    return self.pdfView.collectionView.contentOffset;
}

#pragma mark - PDF Delegate
- (void)pdfView:(FPDFView *)pdfView didSelected:(FPDFPage *)page {
    FImageEditViewController *vc = [[FImageEditViewController alloc] init];
    
    UIImage *img = [[UIImage alloc] init];
    UIGraphicsBeginImageContextWithOptions(page.pageRect.size, YES, UIScreen.mainScreen.scale);
    [page drawInRect:CGRectMake(0, 0, page.pageRect.size.width, page.pageRect.size.height) forContext:UIGraphicsGetCurrentContext()];
    img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    vc.image = img;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pdfView:(FPDFView *)pdfView didDisplay:(FPDFPage *)page {
    if ([self.delegate respondsToSelector:@selector(pdfViewController:displayPage:)]) {
        [self.delegate pdfViewController:self displayPage:page];
    }
}

#pragma mark - Private

@end
